// 基于 Cocos Creator 3.x 的全局事件总线单例，支持发送与接收
// 使用示例：
// import { EventBus } from './common/EventBus';
// EventBus.on('GameStart', (level:number)=>{ /* ... */ }, this);
// EventBus.emit('GameStart', 1);
// EventBus.off('GameStart');
// EventBus.clearTarget(this);

import { EventTarget } from 'cc';

export type EventCallback = (...args: any[]) => void;

class GlobalEventBus {
    private static _instance: GlobalEventBus | null = null;
    private _target: EventTarget = new EventTarget();

    private constructor() {}

    static get instance(): GlobalEventBus {
        if (!this._instance) {
            this._instance = new GlobalEventBus();
        }
        return this._instance;
    }

    // 监听事件
    on(event: string, callback: EventCallback, target?: any): void {
        this._target.on(event, callback, target);
    }

    // 监听一次事件，触发后自动移除
    once(event: string, callback: EventCallback, target?: any): void {
        this._target.once(event, callback, target);
    }

    // 取消监听（不传 callback 时移除该事件所有监听）
    off(event: string, callback?: EventCallback, target?: any): void {
        // Cocos 的 off 允许 callback/target 为空以批量移除
        this._target.off(event, callback as any, target);
    }

    // 解除某个 target 的所有事件绑定（包括 on/once 注册的全部事件）
    clearTarget(target: any): void {
        this._target.targetOff(target);
    }

    // 发送事件
    emit(event: string, ...args: any[]): void {
        this._target.emit(event, ...args);
    }
}

// 对外导出一个简洁的门面，方便直接调用
export const EventBus = {
    on: (event: string, cb: EventCallback, target?: any) => GlobalEventBus.instance.on(event, cb, target),
    once: (event: string, cb: EventCallback, target?: any) => GlobalEventBus.instance.once(event, cb, target),
    off: (event: string, cb?: EventCallback, target?: any) => GlobalEventBus.instance.off(event, cb, target),
    clearTarget: (target: any) => GlobalEventBus.instance.clearTarget(target),
    emit: (event: string, ...args: any[]) => GlobalEventBus.instance.emit(event, ...args),
};

export default EventBus;